package com.secneo.appshare.activities;

import java.io.ByteArrayOutputStream;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.secneo.appshare.R;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.AppRecom;
import com.secneo.appshare.common.AppSharePreference;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.threads.TopListThread;

public class MainTopListActivity extends CommonActivity
{
	public static boolean mRecyleFlag = false;
	private ProgressDialog mProgressDialog = null;
	private TopListThread mTopThread = null;
	private ScrollView mRecomLinear;
	private Gallery mDownGallery;
	private Gallery mHotGallery;
	private Gallery mTalkGallery;
	private Gallery mPromoteGallery;
	private Gallery mGoodGallery;
	private DownListAdapter downListAdapter = null;
	private DownListAdapter hotListAdapter = null;
	private DownListAdapter talkListAdapter = null;
	private DownListAdapter promoteListAdapter = null;
	private DownListAdapter goodListAdapter = null;
	
	private Handler mHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case Constants.MSG_GET_RECOMS_NETWORK_ERROR:
					if (mProgressDialog != null)
					{
						mProgressDialog.dismiss();
						mProgressDialog = null;
					}
					View view = findViewById(R.id.view_network_error);
					view.setVisibility(View.VISIBLE);
					break;

				case Constants.MSG_GET_TOPLIST_FINISH:
					showTopList(mTopThread.getDownList(), mTopThread.getHotList(), 
								mTopThread.getTalkList(), mTopThread.getPromoteList(), mTopThread.getGoodList());
					break;

				case Constants.MSG_GET_TOPLISTICON_FINISH:
					downListAdapter.notifyDataSetChanged();
					hotListAdapter.notifyDataSetChanged();
					talkListAdapter.notifyDataSetChanged();
					promoteListAdapter.notifyDataSetChanged();
					goodListAdapter.notifyDataSetChanged();
					break;
			}
			super.handleMessage(msg);
		}
	};
	
	public class DownListAdapter extends BaseAdapter
	{
		private List<AppRecom> appList;
		int GalItemBg;
		private boolean mStoped;
		
		public DownListAdapter(Context ctx, List<AppRecom> appList)
		{
			this.appList = appList;
			this.mStoped = false;
		}
		
		public void freeDrawable()
		{
			mStoped = true;
			Log.d("MyTag", "Tops bitmaps free !!! ");
			for(int i=0; i<appList.size(); i++)
			{
				if(!appList.get(i).app_icon.contains("buildin"))
				{
					BitmapDrawable a = (BitmapDrawable) appList.get(i).app_icon_drawable;
					if(a!=null && !a.getBitmap().isRecycled())
						a.getBitmap().recycle();
					appList.get(i).app_icon_drawable = null;
				}
			}
			System.gc();
		}
		
		public void setAppList(List<AppRecom> appList)
		{
			this.appList = appList;
		}

		@Override
		public int getCount()
		{
			return appList.size();
		}

		@Override
		public Object getItem(int position)
		{
			return position;
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			if(mStoped)
				return convertView;
			FeedItem feedItem;
			try
			{
				if (convertView == null) 
				{
					View v = LayoutInflater.from(MainTopListActivity.this).inflate(R.layout.appshare_app_toplist_item, null);
					feedItem = new FeedItem();
					feedItem.mAppIcon = (ImageView)v.findViewById(R.id.ivAppIcon);
					feedItem.mAppName = (TextView)v.findViewById(R.id.tvAppName);
					v.setTag(feedItem);
					convertView = v;
				} 
				else 
					feedItem = (FeedItem)convertView.getTag();
				if(position > appList.size()-1)
					return convertView;
				AppRecom appInfo = appList.get(position);
				if (appInfo.app_icon_drawable == null)
					feedItem.mAppIcon.setImageResource(R.drawable.some_app);
				else 
					feedItem.mAppIcon.setImageDrawable(appInfo.app_icon_drawable);
				
				feedItem.mAppIcon.setScaleType(ImageView.ScaleType.FIT_XY);
				feedItem.mAppName.setText(appInfo.app_name);
				feedItem.mAppName.setTextColor(android.graphics.Color.BLACK);
			
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return convertView;
		}
	}
	
	class FeedItem 
	{
		ImageView mAppIcon;
		TextView mAppName;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_toplist);
		setContext(this);
		
		mRecomLinear = (ScrollView) findViewById(R.id.recomList);
		mDownGallery = (Gallery) findViewById(R.id.downList);
		mHotGallery = (Gallery) findViewById(R.id.hotList);
		mTalkGallery = (Gallery) findViewById(R.id.talkList);
		mPromoteGallery = (Gallery) findViewById(R.id.promoteList);
		mGoodGallery = (Gallery) findViewById(R.id.goodList);
		startProgressDialog();
		mTopThread = new TopListThread(MainTopListActivity.this, mHandler, "", 35);
		mTopThread.start();
	}

	@Override
	protected void onPause()
	{
		if(mRecyleFlag)
		{
			//回收资源
			mRecyleFlag = false;
			endChildrenThreads();
		}
		super.onPause();
	}

	@Override
	protected void onNewIntent(Intent intent)
	{
		Boolean needInit = intent.getBooleanExtra("FromGroup", false);
		if(needInit)
		{
			//重新获取资源
			startProgressDialog();
			endChildrenThreads();
			mTopThread = new TopListThread(MainTopListActivity.this, mHandler, "", 35);
			mTopThread.start();
		}
		super.onNewIntent(intent);
	}
	
	private void startProgressDialog()
	{
		View view = findViewById(R.id.view_network_error);
		view.setVisibility(View.GONE);
		mRecomLinear.setVisibility(View.GONE);
		if (mProgressDialog != null)
			mProgressDialog.dismiss();
		mProgressDialog = new ProgressDialog(MainTopListActivity.this);
		mProgressDialog.setMessage("加载中，请稍候...");
		mProgressDialog.setCancelable(false);
		mProgressDialog.show();
	}
	
	private void endChildrenThreads()
	{
		if (mTopThread != null)
		{
			mTopThread.stopRun();
			mTopThread = null;
		}
		
		mDownGallery.setAdapter(null);
		if (downListAdapter != null)
			downListAdapter.freeDrawable();
		
		mHotGallery.setAdapter(null);
		if (hotListAdapter != null)
			hotListAdapter.freeDrawable();
		
		mTalkGallery.setAdapter(null);
		if (talkListAdapter != null)
			talkListAdapter.freeDrawable();
		
		mPromoteGallery.setAdapter(null);
		if (promoteListAdapter != null)
			promoteListAdapter.freeDrawable();
		
		mGoodGallery.setAdapter(null);
		if (goodListAdapter != null)
			goodListAdapter.freeDrawable();
	}
	
	public void showTopList(final List<AppRecom> downList, final List<AppRecom> hotList, 
							final List<AppRecom> talkList, final List<AppRecom> promoteList,
							final List<AppRecom> goodList) 
	{
		if (downList == null && hotList == null && talkList == null && promoteList == null)
		{
			if (mProgressDialog != null)
			{
				mProgressDialog.dismiss();
				mProgressDialog = null;
			}
			return;
		}
		mRecomLinear.setVisibility(View.VISIBLE);
		if (mProgressDialog != null)
		{
			mProgressDialog.dismiss();
			mProgressDialog = null;
		}

		downListAdapter = new DownListAdapter(this, downList);
		mDownGallery.setAdapter(downListAdapter);
		mDownGallery.setSelection(1, true);
		mDownGallery.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView parent, View v, int position, long id)
			{
				try  
				{
					AppRecom appInfo = downList.get(position);
					Intent intent = new Intent(); 
					intent.setClass(MainTopListActivity.this, ApplicationActivity.class);

					Bundle mBundle = new Bundle(); 
					mBundle.putString("package_name", appInfo.package_name);
					mBundle.putInt("n", 20);
					String uid = LocalStore.getLocaleStoreInstance(MainTopListActivity.this).getUid();
					mBundle.putString("uid", uid);
					mBundle.putBoolean("installed_not_addicted", true);
					 
					PackageManager manager = getPackageManager();
					try 
					{
						PackageInfo info = manager.getPackageInfo(appInfo.package_name, 0);
						if (info != null)
							mBundle.putBoolean("user_app_flag", true);
						else
							mBundle.putBoolean("user_app_flag", false);

					 } catch (Exception e) {
						 mBundle.putBoolean("user_app_flag", false);
					 }
					 
					 /* Send the icon */
					mBundle.putString("app_icon", appInfo.app_icon);
					if (appInfo.app_icon_drawable != null) 
					{
						try 
						{
							Bitmap bitmap = ((BitmapDrawable) appInfo.app_icon_drawable).getBitmap();
							ByteArrayOutputStream stream = new ByteArrayOutputStream();

							bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
							byte[] bitmapdata = stream.toByteArray();
							mBundle.putByteArray("app_icon_array", bitmapdata);
							
						} catch (Exception ex) {
							ex.printStackTrace();
							mBundle.putByteArray("app_icon_array", null);
						}

					} else {
						mBundle.putByteArray("app_icon_array", null);
					}
					mBundle.putString("app_name", appInfo.app_name);
					intent.putExtras(mBundle);
					startActivity(intent);
					
				} catch(Exception ex) {
					ex.printStackTrace();
				}
			}
		});
		
		hotListAdapter = new DownListAdapter(this, hotList);
		mHotGallery.setAdapter(hotListAdapter);
		mHotGallery.setSelection(1, true);
		mHotGallery.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView parent, View v, int position, long id)
			{
				try  
				{
					AppRecom appInfo = hotList.get(position);
					Intent intent = new Intent(); 
					intent.setClass(MainTopListActivity.this, ApplicationActivity.class);

					Bundle mBundle = new Bundle(); 
					mBundle.putString("package_name", appInfo.package_name);
					mBundle.putInt("n", 20);
					String uid = LocalStore.getLocaleStoreInstance(MainTopListActivity.this).getUid();
					mBundle.putString("uid", uid);
					mBundle.putBoolean("installed_not_addicted", true);
					 
					PackageManager manager = getPackageManager();
					try 
					{
						PackageInfo info = manager.getPackageInfo(appInfo.package_name, 0);
						if (info != null)
							mBundle.putBoolean("user_app_flag", true);
						else
							mBundle.putBoolean("user_app_flag", false);

					 } catch (Exception e) {
						 mBundle.putBoolean("user_app_flag", false);
					 }
					 
					 /* Send the icon */
					mBundle.putString("app_icon", appInfo.app_icon);
					if (appInfo.app_icon_drawable != null) 
					{
						try 
						{
							Bitmap bitmap = ((BitmapDrawable) appInfo.app_icon_drawable).getBitmap();
							ByteArrayOutputStream stream = new ByteArrayOutputStream();

							bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
							byte[] bitmapdata = stream.toByteArray();
							mBundle.putByteArray("app_icon_array", bitmapdata);
							
						} catch (Exception ex) {
							ex.printStackTrace();
							mBundle.putByteArray("app_icon_array", null);
						}

					} else {
						mBundle.putByteArray("app_icon_array", null);
					}
					mBundle.putString("app_name", appInfo.app_name);
					intent.putExtras(mBundle);
					startActivity(intent);
					
				} catch(Exception ex) {
					ex.printStackTrace();
				}
			}
		});
		
		talkListAdapter = new DownListAdapter(this, talkList);
		mTalkGallery.setAdapter(talkListAdapter);
		mTalkGallery.setSelection(1, true);
		mTalkGallery.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView parent, View v, int position, long id)
			{
				if(!AppSharePreference.isAppShareUserLogined(MainTopListActivity.this))
				{
					Intent intent=new Intent();
					intent.setClass(MainTopListActivity.this, LoginChooseMethodActivity.class);
					startActivity(intent);
				}else
				{
					try 
					{
						AppRecom appInfo = talkList.get(position);
						Intent intent = new Intent(); 
						intent.setClass(MainTopListActivity.this, AppsOtherUserActivity.class);
	
						Bundle mBundle = new Bundle();
						String uid = LocalStore.getLocaleStoreInstance(MainTopListActivity.this).getUid();
						mBundle.putString("uid", uid);
						mBundle.putString("other_uid", appInfo.package_name);
						mBundle.putString("user_icon", appInfo.app_icon);
						mBundle.putString("user_name", appInfo.app_name);
						intent.putExtras(mBundle);
						startActivity(intent);
						
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}
		});

		promoteListAdapter = new DownListAdapter(this, promoteList);
		mPromoteGallery.setAdapter(promoteListAdapter);
		mPromoteGallery.setSelection(1, true);
		mPromoteGallery.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView parent, View v, int position, long id)
			{
				try  
				{
					AppRecom appInfo = promoteList.get(position);
					Intent intent = new Intent(); 
					intent.setClass(MainTopListActivity.this, ApplicationActivity.class);

					Bundle mBundle = new Bundle(); 
					mBundle.putString("package_name", appInfo.package_name);
					mBundle.putInt("n", 20);
					String uid = LocalStore.getLocaleStoreInstance(MainTopListActivity.this).getUid();
					mBundle.putString("uid", uid);
					mBundle.putBoolean("installed_not_addicted", true);
					 
					PackageManager manager = getPackageManager();
					try 
					{
						PackageInfo info = manager.getPackageInfo(appInfo.package_name, 0);
						if (info != null)
							mBundle.putBoolean("user_app_flag", true);
						else
							mBundle.putBoolean("user_app_flag", false);

					 } catch (Exception e) {
						 mBundle.putBoolean("user_app_flag", false);
					 }
					 
					 /* Send the icon */
					mBundle.putString("app_icon", appInfo.app_icon);
					if (appInfo.app_icon_drawable != null) 
					{
						try 
						{
							Bitmap bitmap = ((BitmapDrawable) appInfo.app_icon_drawable).getBitmap();
							ByteArrayOutputStream stream = new ByteArrayOutputStream();

							bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
							byte[] bitmapdata = stream.toByteArray();
							mBundle.putByteArray("app_icon_array", bitmapdata);
							
						} catch (Exception ex) {
							ex.printStackTrace();
							mBundle.putByteArray("app_icon_array", null);
						}

					} else {
						mBundle.putByteArray("app_icon_array", null);
					}
					mBundle.putString("app_name", appInfo.app_name);
					intent.putExtras(mBundle);
					startActivity(intent);
					
				} catch(Exception ex) {
					ex.printStackTrace();
				}
			}
		});
		
		goodListAdapter = new DownListAdapter(this, goodList);
		mGoodGallery.setAdapter(goodListAdapter);
		mGoodGallery.setSelection(1, true);
		mGoodGallery.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView parent, View v, int position, long id)
			{
				try  
				{
					AppRecom appInfo = promoteList.get(position);
					Intent intent = new Intent(); 
					intent.setClass(MainTopListActivity.this, ApplicationActivity.class);

					Bundle mBundle = new Bundle(); 
					mBundle.putString("package_name", appInfo.package_name);
					mBundle.putInt("n", 20);
					String uid = LocalStore.getLocaleStoreInstance(MainTopListActivity.this).getUid();
					mBundle.putString("uid", uid);
					mBundle.putBoolean("installed_not_addicted", true);
					 
					PackageManager manager = getPackageManager();
					try 
					{
						PackageInfo info = manager.getPackageInfo(appInfo.package_name, 0);
						if (info != null)
							mBundle.putBoolean("user_app_flag", true);
						else
							mBundle.putBoolean("user_app_flag", false);

					 } catch (Exception e) {
						 mBundle.putBoolean("user_app_flag", false);
					 }
					 
					 /* Send the icon */
					mBundle.putString("app_icon", appInfo.app_icon);
					if (appInfo.app_icon_drawable != null) 
					{
						try 
						{
							Bitmap bitmap = ((BitmapDrawable) appInfo.app_icon_drawable).getBitmap();
							ByteArrayOutputStream stream = new ByteArrayOutputStream();

							bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
							byte[] bitmapdata = stream.toByteArray();
							mBundle.putByteArray("app_icon_array", bitmapdata);
							
						} catch (Exception ex) {
							ex.printStackTrace();
							mBundle.putByteArray("app_icon_array", null);
						}

					} else {
						mBundle.putByteArray("app_icon_array", null);
					}
					mBundle.putString("app_name", appInfo.app_name);
					intent.putExtras(mBundle);
					startActivity(intent);
					
				} catch(Exception ex) {
					ex.printStackTrace();
				}
			}
		});
	}
}